package com.alibaba.sample.petstore.dal.dao.ibatis;

import org.springframework.orm.ibatis.support.SqlMapClientDaoSupport;

import com.alibaba.sample.petstore.dal.dao.SequenceDao;
import com.alibaba.sample.petstore.dal.dataobject.Sequence;

public class IbatisSequenceDao extends SqlMapClientDaoSupport implements SequenceDao {
    /**
     * This is a generic sequence ID generator that is based on a database table
     * called 'SEQUENCE', which contains two columns (NAME, NEXTID). This
     * approach should work with any database.
     * 
     * @param name The name of the sequence.
     * @return The Next ID
     */
    public synchronized int getNextId(String name) {
        Sequence sequence = new Sequence(name, -1);

        sequence = (Sequence) getSqlMapClientTemplate().queryForObject("getSequence", sequence);

        if (sequence == null) {
            throw new IllegalArgumentException(
                    "Error: A null sequence was returned from the database (could not get next " + name + " sequence).");
        }

        Object parameterObject = new Sequence(name, sequence.getNextId() + 1);

        getSqlMapClientTemplate().update("updateSequence", parameterObject);

        return sequence.getNextId();
    }
}
